/**
 * Created by xinhuang on 15/6/6.
 */
(function (angular) {
  'use strict';

  angular.module('services.customActivity.realtime')
    .service('realtimeServer', realtimeServer)
    .service('timedTask', timedTask);

  function timedTask(realtimeServer, dialogFormService, socketServer, activityManager, $timeout) {
    var that = this;
    var _alerted = false;
    //已注册的定时服务实例列表
    var tasks = [];

    //根据实时页面所加载的模块注册定时请求服务
    that.register = function (serverName) {
      tasks.push(serverName);
    };

    //开始所有任务
    that.start = function () {
      socketServer.socket.on('timer', function () {
        tasks.forEach(function (task) {
          realtimeServer[task].get(function (res) {
            if (res.state === '1005' && is.falsy(_alerted)) {
              dialogFormService.alert('活动已经结束!');
              that.stop();
              _alerted = true;
            }
          });
        });
      });
    };
    //停止所有任务
    that.stop = function () {
      socketServer.socket.removeAllListeners();
      tasks = [];
    };
  }

  function realtimeServer($http) {
    var servers = [
      'businessDayVolume', 'businessTotalVolume', 'businessTimeVolume', 'health',
      'averageProcessTime', 'maxThroughput', 'maxTPS', 'userRechargePreference',
      'businessProvinceVolume', 'upaySuccessRate', 'proBusSuccessRate', 'proSysSuccessRate',
      'allBusSuccessRate', 'allSysSuccessRate', 'provinceAllBusinessProcess'];
    var that = this;

    that.activityId = null;

    //设置活动参数
    that.setActivityId = function (activityId) {
      that.activityId = activityId;
    };

    //生成servers数组中所有模块的http请求方法与data实例
    servers.forEach(function (server) {
      that[server] = {
        data: {},
        get: function (callback) {
          $http.post('/sas/customActivity/realTime/' + server + '/query', { activityId: that.activityId })
            .success(function (res) {
              this.data = res.data;
              if (is.not.undefined(callback)) {
                callback(res);
              }
            }.bind(this));
        }
      };
    });

    that.activityStateCheck = function (activityId) {
      return $http.post('/sas/customActivity/realTime/activityList/check', { activityId: activityId });
    }
  }
})(angular);

